//
//  PositionsTableController.m
//  Futures
//
//  Created by Cheng on 2017/6/26.
//  Copyright © 2017年 Cheng. All rights reserved.
//

#import "PositionsTableController.h"
#import "PositionsCell.h"
#import "OrderViewModel.h"
#import "TransacionViewModel.h"
#define kPositionCellID @"PositionCellID"
#define kGetHoldingOrder @"kGetHoldingOrder"

@interface PositionsTableController ()
{
    NSString *_previousTitle;
    NSMutableArray *_holdingArray;
    BOOL _oneKeyCloseFinish;
}


@property (weak, nonatomic) IBOutlet UILabel *allMoney;

@end

@implementation PositionsTableController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _holdingArray = [NSMutableArray array];
//    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);  //  全部平仓显示出来
    _oneKeyCloseFinish = YES;
    
    
    _previousTitle = self.tabBarController.navigationItem.title;
    
    if (!GLOBAL_INSTANCE.isLogin) {
        return;
    }
    
    [self refreshData];
}

- (void)refreshData{
    if (_oneKeyCloseFinish==NO) {
        return;
    }
    [TransacionViewModel requestHoldingWithBlck:^(id obj) {
        if (!_oneKeyCloseFinish) {
            return;
        }
        _holdingArray = obj;
        NSMutableArray *deleteArr = [NSMutableArray array];
        for (HoldingModel *model in _holdingArray) {
            if (model.Qty == 0) {
                [deleteArr addObject:model];
            }
        }
        // 删除持仓为0的数据
        [_holdingArray removeObjectsInArray:deleteArr];
        
        // 刷新表格
        [self.tableView reloadData];
        
        // 计算总盈亏
        int money = 0;
        for (HoldingModel *model in _holdingArray) {
            money += model.UnrealizedPL;
            MYLog(@"%@",model.properties_aps);
        }
        if (money > 0){
            NSString *str = [NSString stringWithFormat:@"+ %d  元",money];
            self.allMoney.attributedText = [NSString stringWithaString:str bigFont:28 smallFont:21 color:[UIColor redColor]];
        }else{
            NSString *str = [NSString stringWithFormat:@"%d  元",money];
            self.allMoney.attributedText = [NSString stringWithaString:str bigFont:28 smallFont:21 color:[UIColor greenColor]];
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.tabBarController.navigationItem.title = @"我的订单";
    
    self.tabBarController.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTitle:@"订单记录" target:self action:@selector(clickSettlement)];
    
    if (!GLOBAL_INSTANCE.isLogin) {
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    [[JX_GCDTimerManager sharedInstance] scheduledDispatchTimerWithName:kGetHoldingOrder timeInterval:5 queue:nil repeats:YES actionOption:AbandonPreviousAction action:^{
        [weakSelf refreshData];
    }];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    self.tabBarController.navigationItem.title = _previousTitle;
    
    self.tabBarController.navigationItem.rightBarButtonItem = nil;
    
    if ([[JX_GCDTimerManager sharedInstance] existTimer:kGetHoldingOrder]) {
        [[JX_GCDTimerManager sharedInstance] cancelTimerWithName:kGetHoldingOrder];
    }
}



- (void)clickSettlement{
    UIViewController *vc = [[UIStoryboard storyboardWithName:@"Home" bundle:nil] instantiateViewControllerWithIdentifier:@"Settlement"];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexvPath:(NSIndexPath *)indexPath{
    return 155;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _holdingArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PositionsCell *cell = nil;
    
    cell = [tableView dequeueReusableCellWithIdentifier:kPositionCellID forIndexPath:indexPath];
    
    HoldingModel *model = _holdingArray[indexPath.section];
    
    [cell setCellWith:model];
    
    return cell;
}
- (IBAction)clickSetProfit:(id)sender {
}


- (IBAction)clickOneKeyClose:(id)sender {
    _oneKeyCloseFinish = NO;
    [SVProgressHUD dismiss];
    if (_holdingArray.count == 0) {
        _oneKeyCloseFinish = YES;
        return;
    }
    HoldingModel *model = _holdingArray[0];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
    [SVProgressHUD show];
    if ([model.BuySell containsString:@"买"]) {  // 卖出操作
        
        [OrderViewModel requestSendOrderSymbol:model.Symbol Buysell:@"卖出" qty:abs(model.Qty) block:^(id obj) {
            [self.view makeToast:obj];
            [self deleteSectionAnimationWithIndexPath:indexPath];
            [self clickOneKeyClose:nil];
            sleep(0.3);
        }];
    }else{  // 买入操作
        [OrderViewModel requestSendOrderSymbol:model.Symbol Buysell:@"买入" qty:abs(model.Qty) block:^(id obj) {
            [self.view makeToast:obj];
            [self deleteSectionAnimationWithIndexPath:indexPath];
            [self clickOneKeyClose:nil];
            sleep(0.3);
        }];
        
    }
}

- (IBAction)closePosition:(id)sender {
    UIView *view1 = [sender superview];
    UIView *view2 = [view1 superview];
//    NSLog(@"=== %@ %@ %@ %@", [view1 class], [view2 class], [[view2 superview] class], [[[view2 superview] superview] class]);
    NSIndexPath *indexPath = [(UITableView *)[[[view2 superview] superview] superview] indexPathForCell:(PositionsCell *)[view2 superview]];
    NSLog(@"indexPath:--------%@", indexPath);
    
    HoldingModel *model = _holdingArray[indexPath.section];
    
    if ([model.BuySell containsString:@"买"]) {  // 卖出操作
        
        [SVProgressHUD show];
        
        [OrderViewModel requestSendOrderSymbol:model.Symbol Buysell:@"卖出" qty:abs(model.Qty) block:^(id obj) {
            [SVProgressHUD dismiss];
            [self.view makeToast:obj];
            [self deleteSectionAnimationWithIndexPath:indexPath];
        }];
    }else{  // 买入操作
        [SVProgressHUD show];
        
        [OrderViewModel requestSendOrderSymbol:model.Symbol Buysell:@"买入" qty:abs(model.Qty) block:^(id obj) {
            [SVProgressHUD dismiss];
            [self.view makeToast:obj];
            [self deleteSectionAnimationWithIndexPath:indexPath];
        }];
    }
    
}

// 动态删除数据动画
- (void)deleteSectionAnimationWithIndexPath:(NSIndexPath *)indexPath{
    [self.tableView beginUpdates];    // 必须添加 开始更新  和结束更新，中间必须删除 数据
    [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationRight];
    
    [_holdingArray removeObjectAtIndex:indexPath.section];
    [self.tableView endUpdates];
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
